/**
 * 将base64编码的数据转换成Blob形式
 * @param {string} dataUrl 要转换的base64字符串
 */
const base64ToBlob = (dataUrl = '') => {
  try {
    let arr = dataUrl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while(n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  } catch (e) {
    alert(e.message);
  }
}

/**
 * 下载指定base64内容，并生成指定文件名
 * @param {string} filename 最终下载完成后的文件名
 * @param {string} content 要下载的base64文件编码
 */
const download = (filename = 'test.pdf', content) => {
  try {
    let oA = document.createElement('a');
    let blob = base64ToBlob(content);

    oA.download = filename;
    oA.href = URL.createObjectURL(blob);

    oA.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
  } catch (e) {
    alert(e.message);
  }
}

/**
 * 预览
 * @param {string} content 要预览的pdf文件base64编码的字符数据
 */
const preview = (content = '') => {
  try {
    let blob = base64ToBlob(content);
    let link = URL.createObjectURL(blob);
    window.open(link);
  } catch (e) {
    alert(e.message);
  }
}

/**
 * 请求下载
 */
const wantToDownload = () => {
  Ajax()
    .post({
      url : '/users/getPDFText',
      success : function(data) {
        if(data) download('mypdf.pdf', `data:application/pdf;base64,${data}`);
      },
      async : true
    })
}

/**
 * 亲戚预览
 */
const wantToPreview = () => {
  Ajax()
    .post({
      url: '/users/getPDFText',
      success: function (data) {
        if(data) preview(`data:application/pdf;base64,${data}`);
      },
      async: true
    })
}

document.getElementById('btn1').addEventListener('click', wantToDownload, false);
document.getElementById('btn2').addEventListener('click', wantToPreview, false);
document.getElementById('btn3').addEventListener('click', () => {
  let doc = new jsPDF();
  doc.text('Hello world', 10, 10);
  doc.save('a4.pdf');
}, false);